var resolver = require("sandro/resolver")
var render = require("rosa/html4Render").render
var clientMod = require("sandro/clientMod")
var arrayUtils = require("arrayUtils")

var $ = exports

var resolversByMethod = {}

var log = java.util.logging.Logger.getLogger("sandro")

var resolverFor = function(method) {
	if ( ! resolversByMethod[method] ) {
		resolversByMethod[method] = resolver.resolver()
	}
	return resolversByMethod[method]
}

var route = function(method, rule, action) {
	resolverFor(method).push(rule, action)
}

$.unsafeRoute = route

$.htmlRoute = function(method, rule, action) {
	route(method, rule, function(request, response) {
		var rosa = action(request)
		response.status = 200
		response.contentType = "text/html"
		response.writer.print(render(rosa))
	})
}

$.modRoute = function(method, rule) {
	var authorizedModsDependencies = arrayUtils.fromArguments(arguments,2)
	route(method, rule, clientMod.action(authorizedModsDependencies))
}

$.dispatch = function(request, response) {
	var action = resolverFor(request.method).resolve(request.requestURI)
	action(request, response)
}